package pers.youqu.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import pers.youqu.auth.config.OSSProperties;
import pers.youqu.auth.service.ALIAuthService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jason
 * @version 1.0.0
 * @date 2020/12/6 17:24
 * @Description TODO
 */
@Service
@Slf4j
public class ALIAuthServiceImpl implements ALIAuthService {

    private OSSProperties prop;

    private OSS ossClient;

    public ALIAuthServiceImpl(OSSProperties ossProperties, OSS ossClient) {
        this.prop = ossProperties;
        this.ossClient = ossClient;
    }

    @Override
    public Map<String, String> getAliSignature() {
        try {
            // 1.计算过期时间
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime;
            Date expiration = new Date(expireEndTime);

            // 2.设置上传策略
            PolicyConditions policyConds = new PolicyConditions();
            // 2.1.文件大小限制
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            // 2.2.上传目录
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 2.3.生成策略
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            // 2.4.编码
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 3.生成签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            // 4.封装要返回的结果
            Map<String, String> map = new HashMap<>();
            map.put("accessId", prop.getAccessKeyId());
            map.put("host", prop.getHost());
            map.put("policy", encodedPolicy);
            map.put("signature", postSignature);
            map.put("expire", expireEndTime + "");
            map.put("dir", prop.getDir());

            return map;

//            return ALIOSSSignatureDTO.of(prop.getAccessKeyId(), prop.getHost(), encodedPolicy, postSignature, expireEndTime, prop.getDir());
        } catch (Exception e) {
            log.error("上传文件失败，原因：{}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败！", e);
        }
    }
}
